package pl.lsierant.j2me.bipacz.persistent;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Vector;

import pl.lsierant.j2me.bipacz.log.Logger;

public class DeserializationHelper {
    private static final Logger logger = new Logger("DeserializationHelper");

    public static int lastObjectType = -1;
    public static int lastReadType = -1;

    private final DataInputStream in;
    private int versionId;

    public DeserializationHelper(DataInputStream in) throws IOException {
        this.in = in;
        initialize();
    }

    private void initialize() throws IOException {
        logger.log("initialize");
        versionId = in.readInt();
    }

    public Object readObject() throws IOException {
        int readType = in.readInt();
        lastReadType = readType;
        logger.log("readObject: type = " + readType);

        switch (readType) {
        case PersistentObjectType.INTEGER:
            return readInt();
        case PersistentObjectType.STRING:
            return readString();
        case PersistentObjectType.LONG:
            return readLong();
        case PersistentObjectType.VECTOR:
            return readVector();
        case PersistentObjectType.PERSISTENT:
        default:
            return readPersistentObject(readType);
        }
    }

    private Object readPersistentObject(int type) throws IOException {
        lastObjectType = type;
        IPersistent obj = PersistentObjectFactory.getInstance().create(type);
        obj.initialize(in);
        return obj;
    }

    private Integer readInt() throws IOException {
        logger.log("readInt");
        return new Integer(in.readInt());
    }

    private Long readLong() throws IOException {
        logger.log("readLong");
        return new Long(in.readLong());
    }

    private String readString() throws IOException {
        logger.log("readString");
        return in.readUTF();
    }

    private Vector readVector() throws IOException {
        logger.log("readVector");
        Vector v = new Vector();
        int size = in.readInt();
        logger.log("readVector: size = " + size);

        for (int i = 0; i < size; i++) {
            v.addElement(readObject());
        }
        return v;
    }

    public int getVersionId() {
        return versionId;
    }
}
